var area = require('../../data/area')
var api = require('../../config/api.js');
var QQMapWX  = require('../../utils/qqmap-wx-jssdk.min.js')
var comm = require("../../utils/comm.js")
var app = getApp()
var p = 0,
  c = 0,
  d = 0

var qqmapsdk = new QQMapWX({
  key: 'VWEBZ-3NYCW-TXCRD-R66TI-HKPM5-UCBBA' // 必填
});
Page({

  /**
   * 页面的初始数据
   */
  data: {
    deptName: '',
    deptPhone: '',
    deptAddress: '',

    toast1Hidden: true,
    modalHidden: true,
    modalHidden2: true,
    notice_str: '',

    provinceName: [],
    provinceCode: [],
    provinceSelIndex: '',
    cityName: [],
    cityCode: [],
    citySelIndex: '',
    districtName: [],
    districtCode: [],
    districtSelIndex: '',
    showMessage: false,
    messageContent: '',
    showDistpicker: false,

    isAgree: false,

    // 注册商家根据地址获取经纬度
    shopInfo: {
      deptName: '',
      username: '',
      trueName: '',
      deptPhone: '',
      userPhone: '',
      deviceNum: '',
      applyNotes: '',
      deptAddress: '',
      agentCode: '',
      logo: ''
    },
    files1: [],
    lng: '',
    lat: ''
  },

  bindAgreeChange: function (e) {
    this.setData({
      isAgree: !!e.detail.value.length
    });
  },

  toast1Change: function (e) {
    this.setData({
      toast1Hidden: true
    });
  },
  modalChange2: function(e){
    this.setData({
      modalHidden2: true
    });
  },

  //表单提交
  formSubmit: function (e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '是否确认提交',
      confirmColor: "#43CBC9",
      success: (res) => {
        // wx.showLoading({
        //   title: '加载中',
        // })

        var provinceName = this.data.provinceName[this.data.provinceSelIndex]
        var cityName = this.data.cityName[this.data.citySelIndex]
        var districtName = this.data.districtName[this.data.districtSelIndex]
        var deptAddress = provinceName + cityName + districtName + e.detail.value.deptAddress
        console.log(deptAddress)
        var loginAccount = e.detail.value.username
        var deviceNum = e.detail.value.deviceNum
        deviceNum = parseInt(deviceNum)
        var logo = that.data.files1+"";

        if (res.confirm) {
          console.log('for发生了submit事件，携带数据为：', e.detail.value);

          var reg = /^[0-9a-zA-Z]+$/;
          var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;

          if (e.detail.value.deptName.length == 0) {
            wx.showToast({
              title: "商家姓名不能为空！",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.username.length == 0) {
            wx.showToast({
              title: "登录账号不能为空!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (!reg.test(loginAccount)) {
            wx.showToast({
              title: "登录账号只能由字母或数字组成!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.deptPhone.length == 0 || e.detail.value.userPhone.length == 0) {
            wx.showToast({
              title: "手机号码不能为空!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.deptPhone.length != 11 || e.detail.value.userPhone.length != 11) {
            wx.showToast({
              title: "手机号长度不正确!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (!myreg.test(e.detail.value.deptPhone) || !myreg.test(e.detail.value.userPhone)) {
            wx.showToast({
              title: '手机号格式有误！',
              icon: 'none',
              duration: 1500
            })
            return false;
          } else if (e.detail.value.deviceNum.length == 0) {
            wx.showToast({
              title: "设备数量不能为空!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.deviceNum.length < 1) {
            wx.showToast({
              title: "设备数量必须大于1台!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.deptAddress.length == 0) {
            wx.showToast({
              title: "地址不能为空!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.code.length == 0) {
            wx.showToast({
              title: "代理商CODE不能为空!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (that.data.isAgree == false) {
            wx.showToast({
              title: "请阅读相关条款并同意!",
              icon: 'none',
              duration: 2000
            });
            return false;
          }
          //根据地址获取经纬度
          that.geocoder(deptAddress);

          that.setData({
              shopInfo:{
                loginAccount: loginAccount,
                deptName: e.detail.value.deptName,
                username: e.detail.value.username,
                trueName: e.detail.value.trueName,
                deptPhone: e.detail.value.deptPhone,
                userPhone: e.detail.value.userPhone,
                deviceNum: e.detail.value.deviceNum,
                applyNotes: e.detail.value.applyNotes,
                deptAddress: deptAddress,
                agentCode: e.detail.value.code,
                logo: logo
              }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
          wx.hideLoading();
        }
      }
    })
  },
  applyShop: function(){
      var that = this;
      wx.request({
        url: api.BuesNameVer + this.data.shopInfo.loginAccount,
        data: {},
        method: 'GET',
        header: {
          'Accept': 'application/json',
          'ACCESS-TOKEN': wx.getStorageSync('token')
        },

        success: function (res) {
          console.log(2);
          if (res.data.success) {
            wx.showLoading({
              title: '数据提交中',
            })
            console.log(that.data.shopInfo+"---deptName:" + JSON.stringify(that.data.shopInfo));
            wx.request({
              url: api.BuesAdd,
              data: {
                deptName: that.data.shopInfo.deptName,
                username: that.data.shopInfo.username,
                trueName: that.data.shopInfo.trueName,
                deptPhone: that.data.shopInfo.deptPhone,
                userPhone: that.data.shopInfo.userPhone,
                deviceNum: that.data.shopInfo.deviceNum,
                applyNotes: that.data.shopInfo.applyNotes,
                deptAddress: that.data.shopInfo.deptAddress,
                agentCode: that.data.shopInfo.agentCode,
                logo: that.data.shopInfo.logo,
                lng: that.data.lng,
                lat: that.data.lat
              },
              method: 'POST',
              header: {
                'Accept': 'application/json',
                'ACCESS-TOKEN': wx.getStorageSync('token')
              },

              success: (res) => {

                console.log(4);

                wx.showLoading({
                  title: '加载中',
                })

                if (res.data.success) {
                  wx.showModal({
                    title: '提示',
                    content: res.data.msg,
                    confirmColor: "#43CBC9",
                    showCancel: false,
                    success: function (res) {
                      if (res.confirm) {
                        console.log('用户点击确定')
                        wx.navigateBack({})
                      }
                    }
                  });
                  wx.hideLoading();
                } else {
                  wx.showModal({
                    title: '提示',
                    content: res.data.msg,
                    confirmColor: "#43CBC9",
                    showCancel: false,
                    success: function (res) {
                      if (res.confirm) {
                        console.log('用户点击确定')
                        // wx.navigateBack({})
                      }
                    }
                  });
                  wx.hideLoading();
                }
              },

            })

          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: function () {
          wx.hideLoading();
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          });
        },
      })
  },
  formReset: function () {
    this.setData({
      modalHidden2: false,
      isAgree: false,
      showDistpicker: false,

      provinceSelIndex: null,

    });
  },
  geocoder:function(address){
    var _that = this;
    //调用地址解析接口
    qqmapsdk.geocoder({
        //获取表单传入地址
        address: address, //地址参数，例：固定地址，address: '北京市海淀区彩和坊路海淀西大街74号'
        success: function (res) {//成功后的回调
            console.log(res);
            var res = res.result;
            var latitude = res.location.lat;
            var longitude = res.location.lng;
            _that.setData({
                lat: latitude,
                lng: longitude
            })
            _that.applyShop();
            
        },
        fail: function (error) {
            console.error(error);
        },
        complete: function (res) {
            console.log(res);
        }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setAreaData()
  },
  setAreaData: function (p, c, d) {
    var p = p || 0 // provinceSelIndex
    var c = c || 0 // citySelIndex
    var d = d || 0 // districtSelIndex
    // 设置省的数据
    var province = area['100000']
    var provinceName = [];
    var provinceCode = [];
    for (var item in province) {
      provinceName.push(province[item])
      provinceCode.push(item)
    }
    this.setData({
      provinceName: provinceName,
      provinceCode: provinceCode
    })
    // 设置市的数据
    var city = area[provinceCode[p]]
    var cityName = [];
    var cityCode = [];
    for (var item in city) {
      cityName.push(city[item])
      cityCode.push(item)
    }
    this.setData({
      cityName: cityName,
      cityCode: cityCode
    })
    // 设置区的数据
    var district = area[cityCode[c]]
    var districtName = [];
    var districtCode = [];
    for (var item in district) {
      districtName.push(district[item])
      districtCode.push(item)
    }
    this.setData({
      districtName: districtName,
      districtCode: districtCode
    })
  },
  changeArea: function (e) {
    p = e.detail.value[0]
    c = e.detail.value[1]
    d = e.detail.value[2]
    this.setAreaData(p, c, d)
  },
  showDistpicker: function () {
    this.setData({
      showDistpicker: true
    })

  },
  distpickerCancel: function () {
    this.setData({
      showDistpicker: false
    })
  },
  distpickerSure: function (e) {
    this.setData({
      provinceSelIndex: p,
      citySelIndex: c,
      districtSelIndex: d
    })
    this.distpickerCancel()
  },
  showMessage: function (text) {
    var that = this
    that.setData({
      showMessage: true,
      messageContent: text
    })
    setTimeout(function () {
      that.setData({
        showMessage: false,
        messageContent: ''
      })
    }, 3000)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (e) {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //选择商品列表图
  chooseImage: function (e) {
    var that = this;
    var len = that.data.files.length;
    if (len < 8) {
      comm.getUploadImg().then(function (link) {
        if (link !== undefined) {
          that.setData({
            files: that.data.files.concat(link)
          });
        } else (
          wx.showToast({
            title: '图片上传失败',
            icon: "none"
          })
        )
      })
    } else {
      wx.showToast({
        title: '图片数量已达到最大限制',
        icon: "none"
      })
    }


  },

  //选择商品主图
  chooseImage1: function (e) {
    var that = this;
    var len = that.data.files1.length;
    if (len < 1) {
      comm.getUploadImg().then(function (link) {
        console.log("----------"+ link);
        if (link !== undefined) {
          that.setData({
            files1: that.data.files1.concat(link)
          });
        } else (
          wx.showToast({
            title: '图片上传失败',
            icon: "none"
          })
        )
      })
    } else {
      wx.showToast({
        title: '图片数量已达到最大限制',
        icon: "none"
      })
    }

  },

  //预览商品列表图片
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },

  //预览商品主图片
  previewImage1: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files1 // 需要预览的图片http链接列表
    })
  },
  //删除列表图片
  deleteImage: function (e) {
    var that = this;
    var files = that.data.files;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      confirmColor: "#43CBC9",
      success: function (res) {
        if (res.confirm) {
          console.log('点击确定了');
          files.splice(index, 1);
        } else if (res.cancel) {
          console.log('点击取消了');
          return false;
        }
        that.setData({
          files
        });
      }
    })
  },

  //删除主图片
  deleteImage1: function (e) {
    var that = this;
    var files1 = that.data.files1;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      confirmColor: "#43CBC9",
      success: function (res) {
        if (res.confirm) {
          console.log('点击确定了');
          files1.splice(index, 1);
        } else if (res.cancel) {
          console.log('点击取消了');
          return false;
        }
        that.setData({
          files1
        });
      }
    })
  }
})